﻿// Copyright (c) 2007-2021 西安交通信息投资营运有限公司 版权所有
// 作者:吕艳阳

using DevExpress.Utils.Design;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.Utils.Menu;
using XCI.Core;
using XCI.Helper;
using XCI.Setting;
using DevExpress.XtraPivotGrid;

namespace XCI.Windows
{
    [System.ComponentModel.DesignerCategory("Code")]
    public class PivotGridControlPlus : PivotGridControl, ISettingSerializer
    {
        private Type _modelType;
        private ApiModel _apiModelInfo;

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public SettingStoreManager SettingManager { get; set; }

        /// <summary>
        /// 配置标识
        /// </summary>
        [Category("XCI"), Description("配置标识")]
        [SmartTagProperty("配置标识", "XCI", SmartTagActionType.RefreshAfterExecute)]
        public virtual string Id { get; set; } = $"pivot-grid-{StringHelper.Guid()}";

        /// <summary>
        /// 允许自定义配置
        /// </summary>
        [Category("XCI"), Description("允许自定义配置"), DefaultValue(true)]
        [SmartTagProperty("允许自定义配置", "XCI", SmartTagActionType.RefreshAfterExecute)]
        public bool AllowCustomSetting { get; set; } = true;

        [Category("XCI"), Description("自动加载配置"), DefaultValue(true)]
        [SmartTagProperty("自动加载配置", "XCI", SmartTagActionType.RefreshAfterExecute)]
        public bool AutoLoadSetting { get; set; } = true;

        /// <summary>
        /// 实体类型
        /// </summary>
        [Browsable(false), Description("实体类型"), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual Type ModelType
        {
            get => _modelType;
            set
            {
                _modelType = value;
                if (WinFormHelper.IsDesignMode()) return;
                _apiModelInfo = ApiModelManager.Get(ModelType);
            }
        }

        /// <summary>
        /// 实体元数据
        /// </summary>
        [Browsable(false), Description("实体元数据"),
         DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual ApiModel ApiModelInfo => _apiModelInfo;

        [Category("XCI"), Description("加载配置之前事件")]
        public event EventHandler<EventArgs> BeforeRestoreLayout;

        [Category("XCI"), Description("加载配置之后事件")]
        public event EventHandler<EventArgs> AfterRestoreLayout;

        [Category("XCI"), Description("控件开始初始化事件")]
        public event EventHandler<EventArgs> BeforeInitialize;
        [Category("XCI"), Description("控件初始化结束事件")]
        public event EventHandler<EventArgs> AfterInitialize;


        protected virtual void OnBeforeInitialize()
        {
            BeforeInitialize?.Invoke(this, EventArgs.Empty);
        }

        protected virtual void OnAfterInitialize()
        {
            AfterInitialize?.Invoke(this, EventArgs.Empty);
        }

        public PivotGridControlPlus()
        {
            if (WinFormHelper.IsDesignMode())
            {
                this.OptionsLayout.Columns.StoreAllOptions = true;
                this.OptionsLayout.StoreAppearance = true;
            }
        }

        protected override async void OnCreateControl()
        {
            base.OnCreateControl();
            if (WinFormHelper.IsDesignMode()) return;

            OnBeforeInitialize();

            //初始化表格配置
            InitGridSetting();

            //加载表格配置
            if (AutoLoadSetting)
            {
                await LoadGridSetting();
            }

            OnAfterInitialize();
        }


        public async Task LoadGridSetting()
        {
            if (SettingManager == null) SettingManager = new SettingStoreManager(this, Id);

            if (!string.IsNullOrEmpty(Id))
            {
                BeforeRestoreLayout?.Invoke(this, EventArgs.Empty);
                await SettingManager.LoadCurrentAsync();
                AfterRestoreLayout?.Invoke(this, EventArgs.Empty);
            }
            else
            {
                Debug.WriteLine("请指定有效的PivotGridControlPlus-Id");
            }
        }

        public void InitGridSetting()
        {
            var allowCustomization = AllowCustomSetting && AppDefaultSettings.AllowCustomGridControlSetting;
            if (!allowCustomization) return;

            this.PopupMenuShowing += (s, e) =>
            {
                if (e.MenuType != PivotGridMenuType.HeaderArea) return;

                var customItem = new DXMenuItem("设置", (o, a) => ShowSettingForm(), R.GridSettingImage16) { BeginGroup = true };
                e.Menu.Items.Add(customItem);
            };
            this.KeyDown += (s, e) =>
            {
                if (e.Control && e.Shift && e.Alt && e.KeyCode == Keys.F12)
                {
                    ShowSettingForm();
                    e.Handled = true;
                }
            };
        }

        /// <summary>
        /// 显示配置窗口
        /// </summary>
        public void ShowSettingForm()
        {
            var settingFrm = new FrmSettingPivotGridForm();
            settingFrm.Init(this);
            settingFrm.Show();

        }

        /// <summary>
        /// 自动生成表格列
        /// </summary>
        public void AutoBuildColumn()
        {
            var modelInfo = ApiModelInfo;
            if (modelInfo == null) return;
            Fields.Clear();
            for (var index = 0; index < modelInfo.Propertys.Count; index++)
            {
                var item = modelInfo.Propertys[index];
                var col = item;
                PivotGridField column = new PivotGridField();
                column.Area = DevExpress.XtraPivotGrid.PivotArea.ColumnArea;
                column.AreaIndex = index;
                column.Name = $"pivotGridField{index}";
                column.FieldName = col.Name;
                column.Caption = col.Caption ?? col.Name;
                column.Visible = col.Visable;
                Fields.Add(column);
            }
        }

        /// <summary>
        /// 加载配置到控件
        /// </summary>
        /// <param name="xmlFile">xml文件路径</param>
        public void RestoreLayout(string xmlFile)
        {
            RestoreLayoutFromXml(xmlFile);
        }

        /// <summary>
        /// 保存控件配置
        /// </summary>
        /// <param name="xmlFile">xml文件路径</param>
        public void SaveLayout(string xmlFile)
        {
            SaveLayoutToXml(xmlFile);
        }
    }
}